<template>
  <j-select-depart
    v-model="departId"
    :customReturnField="customReturnField"
    :disabled="disabled"
    :multi="record.options.multiple"
  >
  </j-select-depart>
</template>
<script>
import { mapGetters } from 'vuex'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
export default {
  name: 'Dept',
  components: {
    JSelectDepart
  },
  props: ['record', 'value', 'disabled'],
  data() {
    return {
      departId: '',
      customReturnField: 'orgCode'
    }
  },
  watch: {
    value(newValue) { // 用户值改变时   获取用户真实姓名
      this.departId = newValue
    },
    'record.options.defaultValue'(newValue) {
      if (newValue === '${departName}' || newValue === '${departCode}') {
        const orgCodes = this.getIdOrCode(this.departs(), 'orgCode')
        this.customReturnField = 'orgCode'
        this.departId = orgCodes.join(',')
        this.$emit('change', this.departId)
      } else if (newValue === '${id}') {
        const ids = this.getIdOrCode(this.departs(), 'id')
        this.departId = ids.join(',')
        this.customReturnField = 'id'
        this.$emit('change', this.departId)
      } else {
        this.customReturnField = 'orgCode'
        this.$emit('change', newValue)
      }
    },
    departId(newValue) {
      this.$emit('change', newValue)
    }
  },
  methods: {
    ...mapGetters(['departs']),
    getIdOrCode(list, key) {
      const ids = []
      list.forEach(element => {
        ids.push(element[key])
      })
      return ids
    }
  },
  mounted() {
    const defaultValue = this.record.options.defaultValue
    if (this.value && this.value !== defaultValue) {
      this.departId = this.value
    } else {
      if (defaultValue === '${departName}' || defaultValue === '${departCode}') {
        const orgCodes = this.getIdOrCode(this.departs(), 'orgCode')
        this.customReturnField = 'orgCode'
        this.departId = orgCodes.join(',')
        this.$emit('change', this.departId)
      } else if (defaultValue === '${id}') {
        const ids = this.getIdOrCode(this.departs(), 'id')
        this.departId = ids.join(',')
        this.customReturnField = 'id'
        this.$emit('change', this.departId)
      }
    }
  }
}
</script>
